<script lang="ts" setup>
import Selector from "@/components/Selector.vue";
import Inputter from "@/components/Inputter.vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { onMounted, reactive, ref } from 'vue';
import instance from '@/utils/request';
import { useAdminStore } from "@/stores/admin";
import router from "@/router/router";

// 管理员客房信息修改页面
onMounted(() => {
  init();
  price_init();
});

const admin = useAdminStore();

let room_id = ref("");
let room_type = ref("");
// 客房价格在价格数字后加上“元/间”
let room_price = ref("");

// 是否禁用输入框
let disabled = ref(true);

let dialogVisible = ref(false);
let dialogVisibleUpdate = ref(false);
let dialogVisibleAdd = ref(false);
let dialogVisibleDelete = ref(false);

// 搜索
const room_id_select = ref("");
const room_type_select = ref("");
const room_price_select = ref("");
const room_status_select = ref("全部");

// 各类型的客房价格
let standard_double_price = ref();
let superior_double_price = ref();
let business_double_price = ref();
let standard_twin_price = ref();
let superior_twin_price = ref();
let business_twin_price = ref();
let standard_price = ref();
let standard_family_price = ref();
let superior_family_price = ref();

// 类型的下拉框（查询）
const room_type_options = [
  { value:'全部', label:'全部' },
  { value:'标准间', label:'标准间' },
  { value:'标准大床房', label:'标准大床房' },
  { value:'高级大床房', label:'高级大床房' },
  { value:'商务大床房', label:'商务大床房' },
  { value:'标准双床房', label:'标准双床房' },
  { value:'高级双床房', label:'高级双床房' },
  { value:'商务双床房', label:'商务双床房' },
  { value:'标准家庭房', label:'标准家庭房' },
  { value:'高级家庭房', label:'高级家庭房' }
];

// 类型的下拉框（表单）
const room_type_form_options = [
  { value:'标准间', label:'标准间' },
  { value:'标准大床房', label:'标准大床房' },
  { value:'高级大床房', label:'高级大床房' },
  { value:'商务大床房', label:'商务大床房' },
  { value:'标准双床房', label:'标准双床房' },
  { value:'高级双床房', label:'高级双床房' },
  { value:'商务双床房', label:'商务双床房' },
  { value:'标准家庭房', label:'标准家庭房' },
  { value:'高级家庭房', label:'高级家庭房' }
];

// 状态的下拉框（查询）
const room_status_options = [
  { value:'全部', label:'全部' },
  { value:'空闲', label:'空闲' },
  { value:'待支付', label:'待支付' },
  { value:'已入住', label:'已入住' },
  { value:'退房中', label:'退房中' },
  { value:'已删除', label:'已删除' }
];

interface Data {
  room_id: string
  room_type: string
  room_price: string
  room_status: string
}

// 不同状态不同样式
const rowClassName = ({row, rowIndex,}: {
  row: Data
  rowIndex: number
}) => {
  if (row.room_status === '空闲') {
    return 'color-admin-edit-room-1';
  }
  else if (row.room_status === '已删除') {
    return 'color-admin-edit-room-2';
  }
  return 'color-admin-edit-room-3';
}

// 数据
let tableData = [];

// 条件查询
const filterTableData = ref();
function filter() {
  filterTableData.value = tableData.filter((data) =>
      (!room_id_select.value || data.room_id.toString().includes(room_id_select.value)) &&
      (room_type_select.value === '全部' || data.room_type.includes(room_type_select.value)) &&
      (!room_price_select.value || data.room_price.includes(room_price_select.value)) &&
      (room_status_select.value === '全部' || data.room_status.includes(room_status_select.value))
  );
}

interface UpdateRuleForm {
  room_type: string
  room_price: string
}

interface AddRuleForm {
  room_id_start: string
  room_id_end: string
  room_type: string
  room_price: string
}

const ruleFormRef = ref<FormInstance>();

const updateRuleForm = reactive<UpdateRuleForm>({
  room_type: '',
  room_price: '',
});

const addRuleForm = reactive<AddRuleForm>({
  room_id_start: '',
  room_id_end: '',
  room_type: '',
  room_price: null
});

// 房间号验证
const id_start = (rule: any, value: any, callback: any) => {
  if(value === '') {
    callback(new Error('房间号不能为空！'));
  }

  if(value < 100 || value > 999) {
    callback(new Error('三位数房间号'));
  }

  if((value < 100 || value > 137) && (value < 200 || value > 237) &&
      (value < 300 || value > 337) && (value < 400 || value > 437) &&
      (value < 500 || value > 537) && (value < 600 || value > 637)) {
    callback(new Error('非法房间号'));
  }

  if(addRuleForm.room_id_end != '') {
    if(value > addRuleForm.room_id_end) {
      callback(new Error('非法房间号'));
    }
  }
  callback();
}
const id_end = (rule: any, value: any, callback: any) => {
  if(value === '') {
    callback(new Error('房间号不能为空！'));
  }

  if(value < 100 || value > 999) {
    callback(new Error('三位数房间号'));
  }

  if((value < 100 || value > 137) && (value < 200 || value > 237) &&
      (value < 300 || value > 337) && (value < 400 || value > 437) &&
      (value < 500 || value > 537) && (value < 600 || value > 637)) {
    callback(new Error('非法房间号'));
  }

  if(addRuleForm.room_id_start != '') {
    if(value < addRuleForm.room_id_start) {
      callback(new Error('非法房间号'));
    }
  }
  callback();
}

const updateRules = reactive<FormRules<UpdateRuleForm>>({
  room_type: [
    { required: true, message: '类型不能为空！', trigger: 'blur' }
  ],
  room_price: [
    { required: true, message: '价格不能为空！', trigger: 'blur' },
    { type: 'number', message: '请输入正确的价格！', trigger: 'blur' }
  ]
});

const addRules = reactive<FormRules<AddRuleForm>>({
  room_id_start: [
    { required: true, message: '房间号不能为空！', trigger: 'blur' },
    { validator: id_start, trigger:'blur' }
  ],
  room_id_end: [
    { required: true, message: '房间号不能为空！', trigger: 'blur' },
    { validator: id_end, trigger:'blur' }
  ],
  room_type: [
    { required: true, message: '类型不能为空！', trigger: 'blur' }
  ],
  room_price: [
    { required: true, message: '价格不能为空！', trigger: 'blur' },
    { type: 'number', message: '请输入正确的价格！', trigger: 'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if(dialogVisibleUpdate.value) update();
      if(dialogVisibleAdd.value) add();
      if(dialogVisibleDelete.value) deleteBatch();
    }
  });
}

function open(id) {
  // 打开确认对话框
  dialogVisible.value = true;
  room_id.value = id.toString();
}

function openUpdate(id, type, price) {
  // 打开修改确认对话框
  dialogVisibleUpdate.value = true;
  room_id.value = id.toString();
  updateRuleForm.room_price = Number(price.slice(0, -3));
  updateRuleForm.room_type = type;
}

function openAdd() {
  // 打开新建确认对话框
  dialogVisibleAdd.value = true;
}

function openDelete() {
  // 打开删除确认对话框
  dialogVisibleDelete.value = true;
}

function close () {
  // 关闭确认对话框
  room_id.value = "";
  dialogVisible.value = false;
  dialogVisibleUpdate.value = false;
  dialogVisibleAdd.value = false;
  dialogVisibleDelete.value = false;
}

function roomPrice() {
  // 根据选择的客房类型返回客房价格
  disabled.value = false;
  switch(addRuleForm.room_type) {
    case "标准间": addRuleForm.room_price = standard_price.value;break;
    case "标准大床房": addRuleForm.room_price = standard_double_price.value;break;
    case "高级大床房": addRuleForm.room_price = superior_double_price.value;break;
    case "商务大床房": addRuleForm.room_price = business_double_price.value;break;
    case "标准双床房": addRuleForm.room_price = standard_twin_price.value;break;
    case "高级双床房": addRuleForm.room_price = superior_twin_price.value;break;
    case "商务双床房": addRuleForm.room_price = business_twin_price.value;break;
    case "标准家庭房": addRuleForm.room_price = standard_family_price.value;break;
    case "高级家庭房": addRuleForm.room_price = superior_family_price.value;break;
  }
  if(addRuleForm.room_price == 0) {
    addRuleForm.room_price = null;
  }
  if(addRuleForm.room_price != null) {
    disabled.value = true;
  }

  switch(updateRuleForm.room_type) {
    case "标准间": updateRuleForm.room_price = standard_price.value;break;
    case "标准大床房": updateRuleForm.room_price = standard_double_price.value;break;
    case "高级大床房": updateRuleForm.room_price = superior_double_price.value;break;
    case "商务大床房": updateRuleForm.room_price = business_double_price.value;break;
    case "标准双床房": updateRuleForm.room_price = standard_twin_price.value;break;
    case "高级双床房": updateRuleForm.room_price = superior_twin_price.value;break;
    case "商务双床房": updateRuleForm.room_price = business_twin_price.value;break;
    case "标准家庭房": updateRuleForm.room_price = standard_family_price.value;break;
    case "高级家庭房": updateRuleForm.room_price = superior_family_price.value;break;
  }
}

function init() {
  // 初始化
  instance.request({
    url: 'admin/roommanage/editroom/init',
    method: 'POST',
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "初始化失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          tableData = response.data.data;
          filterTableData.value = tableData;
          addRuleForm.room_type = "全部";
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "初始化失败！",
          type: "error"
        });
        setTimeout(() => {
          init();
        }, 2000 );
      });
}

function price_init() {
  // 价格的初始化
  instance.request({
    url: 'admin/roommanage/editroom/priceInit',
    method: 'POST',
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "初始化失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          //console.log(response.data);
          standard_double_price.value = Number(response.data.data[0].standard_double_price.slice(0, -3));
          superior_double_price.value = Number(response.data.data[0].superior_double_price.slice(0, -3));
          business_double_price.value = Number(response.data.data[0].business_double_price.slice(0, -3));
          standard_twin_price.value = Number(response.data.data[0].standard_twin_price.slice(0, -3));
          superior_twin_price.value = Number(response.data.data[0].superior_twin_price.slice(0, -3));
          business_twin_price.value = Number(response.data.data[0].business_twin_price.slice(0, -3));
          standard_price.value = Number(response.data.data[0].standard_price.slice(0, -3));
          standard_family_price.value = Number(response.data.data[0].standard_family_price.slice(0, -3));
          superior_family_price.value = Number(response.data.data[0].superior_family_price.slice(0, -3));
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "初始化失败！",
          type: "error"
        });
        setTimeout(() => {
          price_init();
        }, 2000 );
      });
}

function update() {
  // 修改客房信息
  instance.request({
    url: 'admin/roommanage/editroom/update',
    method: 'POST',
    data: {
      room_id: room_id.value,
      room_type: updateRuleForm.room_type,
      room_price: updateRuleForm.room_price + "元/间"
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "修改失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          dialogVisibleUpdate.value = false;
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
        }
        init();
        price_init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "修改失败！",
          type: "error"
        });
      });
}

function add() {
  // 添加客房
  instance.request({
    url: 'admin/roommanage/newroom/add',
    method: 'POST',
    data: {
      room_id_start: addRuleForm.room_id_start,
      room_id_end: addRuleForm.room_id_end,
      room_type: addRuleForm.room_type,
      room_price: addRuleForm.room_price + "元/间",
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "添加失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_room_id") {
          ElMessage({
            message: "房间号已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "添加成功！",
            type: "success"
          });
          dialogVisibleAdd.value = false;
          init();
          price_init();
          roomPrice();
          location.reload();
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "添加失败！",
          type: "error"
        });
      });
}

function Delete() {
  // 删除客房
  instance.request({
    url: 'admin/roommanage/editroom/delete',
    method: 'POST',
    data: {
      room_id: room_id.value
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "处理失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          dialogVisible.value = false;
          ElMessage({
            message: "处理成功！",
            type: "success"
          });
          init();
          price_init();
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "处理失败！",
          type: "error"
        });
      });
}

function deleteBatch() {
  // 批量删除
  instance.request({
    url: 'admin/roommanage/editroom/deleteBatch',
    method: 'POST',
    data: {
      room_id_start: addRuleForm.room_id_start,
      room_id_end: addRuleForm.room_id_end
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "处理失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          dialogVisibleDelete.value = false;
          ElMessage({
            message: "处理成功！",
            type: "success"
          });
          init();
          price_init();
          location.reload();
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "处理失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      align-center
      width="18%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <span>确认删除</span>
    <div class="cancel-confirm">
      <el-button color="#568fc1" plain @click="close">
        <span>取消</span>
      </el-button>

      <el-button color="#568fc1" class="button-color" @click="Delete">
        <span>确认</span>
      </el-button>
    </div>
  </el-dialog>

  <el-dialog
      v-model="dialogVisibleUpdate"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="updateRuleForm"
        :rules="updateRules"
    >
      <el-form-item label="客房类型：" prop="room_type">
        <selector :options="room_type_form_options" width="200"
                  v-model="updateRuleForm.room_type" @change="roomPrice"/>
      </el-form-item>

      <el-form-item label="客房价格：" prop="room_price">
        <inputter width="200" disabled
                  v-model.number="updateRuleForm.room_price"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>

        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>修改</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="dialogVisibleAdd"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="addRuleForm"
        :rules="addRules"
    >
      <el-form-item label="房间号" required>
        <el-col :span="10">
          <el-form-item prop="room_id_start">
            <inputter width="100" v-model.number="addRuleForm.room_id_start"/>
          </el-form-item>
        </el-col>

        <el-col class="text" :span="2">
          <span>-</span>
        </el-col>

        <el-col :span="10">
          <el-form-item prop="room_id_end">
            <inputter width="100" v-model.number="addRuleForm.room_id_end"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="客房类型：" prop="room_type">
        <selector :options="room_type_form_options" width="216"
                  @change="roomPrice()" v-model="addRuleForm.room_type"/>
      </el-form-item>

      <el-form-item label="客房价格：" prop="room_price">
        <inputter width="216" v-model.number="addRuleForm.room_price"
                  :disabled="disabled"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>

        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>添加</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="dialogVisibleDelete"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="addRuleForm"
        :rules="addRules"
    >
      <el-form-item label="房间号" required>
        <el-col :span="10">
          <el-form-item prop="room_id_start">
            <inputter width="100" v-model.number="addRuleForm.room_id_start"/>
          </el-form-item>
        </el-col>

        <el-col class="text" :span="2">
          <span>-</span>
        </el-col>

        <el-col :span="10">
          <el-form-item prop="room_id_end">
            <inputter width="100" v-model.number="addRuleForm.room_id_end"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>

        <el-button type="danger" plain
                   @click="submitForm(ruleFormRef)">
          <span>删除</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <div class="select">
    <span>房间号：</span>
    <inputter width="100" v-model="room_id_select"/>

    &emsp;&emsp;<span>客房类型：</span>
    <selector :options="room_type_options" width="100" v-model="room_type_select"/>

    &emsp;&emsp;<span>客房价格：</span>
    <inputter width="100" v-model="room_price_select"/>

    &emsp;&emsp;<span>状态：</span>
    <selector :options="room_status_options" width="100" v-model="room_status_select"/>

    &emsp;&emsp;&emsp;
    <el-button color="#568fc1" class="button-color" @click="filter">
      <span>搜索</span>
    </el-button>
    <el-button color="#568fc1" class="button-color" @click="openAdd">
      <span>添加</span>
    </el-button>
    <el-button type="danger" plain @click="openDelete">
      <span>删除</span>
    </el-button>
  </div>
  <div class="table">
    <el-table
        header-row-style="color: #000000; background-color: #f0f0f0;"
        height="600"
        style="width: 100%"
        :data="filterTableData"
        :row-class-name="rowClassName"
    >
      <el-table-column prop="room_id" label="房间号" width="220"/>
      <el-table-column prop="room_type" label="客房类型" width="220"/>
      <el-table-column prop="room_price" label="客房价格" width="220"/>
      <el-table-column prop="room_status" label="状态" width="220"/>

      <el-table-column align="right" fixed="right" width="200">
        <template #default="scope">
          <el-button v-if="scope.row.room_status == '空闲'"
                     color="#568fc1" class="button-color"
                     @click="openUpdate(scope.row.room_id, scope.row.room_type, scope.row.room_price)">
            <span>修改</span>
          </el-button>

          <el-button v-if="scope.row.room_status == '空闲'"
                     type="danger" plain
                     @click="open(scope.row.room_id)">
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.select {
  padding-top: 2vh;
  padding-left: 8vh;
  padding-right: 5vh;
  /* border: 1px solid black; */
}
.table {
  padding: 1vh 5vh 5vh;
  /* border: 1px solid black; */
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
.cancel-confirm {
  padding-top: 1vh;
  text-align: center;
}
.text {
  text-align: center;
}
</style>

<style>
.el-table .color-admin-edit-room-1 {
  --el-table-tr-bg-color: #C1FFC1;
  --el-table-row-hover-bg-color: #C1FFC1;
}
.el-table .color-admin-edit-room-2 {
  --el-table-tr-bg-color: #f0f0f0;
  --el-table-row-hover-bg-color: #f0f0f0;
}
.el-table .color-admin-edit-room-3 {
  --el-table-tr-bg-color: #e4f7fb;
  --el-table-row-hover-bg-color: #e4f7fb;
}
</style>